package com.nuanshui.heatedloan.credit.rabbitmq;

import com.nuanshui.framework.lang.DateUtil;
import com.nuanshui.framework.springContext.SpringPropertiesUtil;
import com.nuanshui.framework.utils.LogUtil;
import com.nuanshui.heatedloan.constant.RabbitMqQueue;
import com.nuanshui.heatedloan.credit.constant.BorrowType;
import com.nuanshui.heatedloan.credit.constant.CalculateLateFeeRequest;
import com.nuanshui.heatedloan.credit.constant.OrderType;
import com.nuanshui.heatedloan.credit.facade.CustomerProduceService;
import com.nuanshui.heatedloan.credit.facade.PayOrderInfoService;
import com.nuanshui.heatedloan.credit.facade.job.PayOrderJobService;
import com.nuanshui.heatedloan.credit.model.LightLoanProductInfo;
import com.nuanshui.heatedloan.credit.model.SingleLoanProductInfo;
import com.nuanshui.heatedloan.credit.request.OrderJobParams;
import com.nuanshui.heatedloan.credit.utils.CalculateLoanAmt;
import com.nuanshui.heatedloan.credit.vo.PayOrderInfoVO;
import com.nuanshui.heatedloan.middleware.rabbitmq.RabbitmqMessageHandler;
import com.nuanshui.heatedloan.middleware.rabbitmq.annotation.MqMessageHandler;
import com.nuanshui.heatedloan.task.facade.constant.TaskEnum;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

/**
 * Created by wangxw on 2017/7/25.
 * 贷款到期消息队列
 * 每笔订单最多执行一次
 */

@MqMessageHandler(RabbitMqQueue.RABBIT_MQ_REFUND_EXPIRE_JOB)
public class DealExpireRefundHandler implements RabbitmqMessageHandler {

    private static Logger logger = LoggerFactory.getLogger("DealExpireRefundHandler");

    @Autowired
    private PayOrderInfoService payOrderInfoService;

    @Autowired
    private PayOrderJobService payOrderJobService;

    @Autowired
    private CustomerProduceService customerProduceService;



    public void onMessage(Message message, Channel channel ) throws Exception{
        try{
            //需要做以下事情
            int hour=Integer.parseInt(SpringPropertiesUtil.getPropertiestValue("credit.reminder.hour"));
            LogUtil.info(logger, "------开始提醒的时间为"+hour+"------");
            LogUtil.info(logger, "-------------开始处理订单到期-----------");
            byte[] body = message.getBody();
            String orderNum = new String(body);
            if (orderNum.endsWith("\"")) {
                orderNum = orderNum.substring(1, orderNum.length() - 1);
            }
            LogUtil.info(logger, String.format("---------------------orderNum : %s-----------", orderNum));
            PayOrderInfoVO payOrderInfoVO=payOrderInfoService.loadVOByOrderNo(orderNum);
            this.updateLateFee(payOrderInfoVO);
            //生成逾期提醒的定时任务
            this.createQuartz(payOrderInfoVO,hour);
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }
    }

    /***
     * 更新逾期信息
     * @param payOrderInfoVO
     */
    private void updateLateFee(PayOrderInfoVO payOrderInfoVO){
        LogUtil.info(logger, "---------开始更新数据库逾期相关信息---------");
        CalculateLateFeeRequest calculateLateFeeRequest=new CalculateLateFeeRequest();
        //calculateLateFeeRequest.setBeginDay(0);
        calculateLateFeeRequest.setBorrowType(payOrderInfoVO.getBorrowType());
        calculateLateFeeRequest.setLateDay(1);
        calculateLateFeeRequest.setLoanAmt(payOrderInfoVO.getLoanAmount());
        calculateLateFeeRequest.setPayAmt(0);
        if(BorrowType.SINGLELOAN ==payOrderInfoVO.getBorrowType()){
            SingleLoanProductInfo singleLoanProductInfo =customerProduceService.
                    getSingleLoanProductInfo();
            calculateLateFeeRequest.setSingleFeeRateSmall(singleLoanProductInfo.getLateFeeBefore());
            LogUtil.info(logger, String.format("---------------------LateFeeBefore:%s-----------", singleLoanProductInfo.getLateFeeBefore()));
            calculateLateFeeRequest.setSingleFeeRateBig(singleLoanProductInfo.getLateFeeAfter());
            calculateLateFeeRequest.setBeginDay(singleLoanProductInfo.getBeforeDay());
            LogUtil.info(logger, String.format("---------------------LateFeeAfter:%s-----------", singleLoanProductInfo.getLateFeeAfter()));
        }else if(BorrowType.LIGHTLOAN==payOrderInfoVO.getBorrowType()){
            LightLoanProductInfo lightLoanProductInfo=customerProduceService.
                    getLightLoanProductInfo();
            calculateLateFeeRequest.setLightFeeRate(lightLoanProductInfo.getLateFee());
            LogUtil.info(logger, String.format("---------------------LateFee:%s-----------", lightLoanProductInfo.getLateFee()));
            calculateLateFeeRequest.setBeginDay(lightLoanProductInfo.getBeforeDay());
        }
        int lateFee= CalculateLoanAmt.calculateLateFee(calculateLateFeeRequest);
        payOrderInfoService.updateLateInfoByOrderNo(payOrderInfoVO.getOrderNo(),lateFee,1,OrderType.OVERDUEPAYMENT);
        //sql去更新状态
        LogUtil.info(logger, "---------处理订单到期更新数据库记录完成---------");
        //更新数据库的状态为逾期，并计算逾期费的相关信息
    }

    public void createQuartz(PayOrderInfoVO payOrderInfoVO,int hour){
        LogUtil.info(logger, "-------------开始生成第一天的逾期定时任务-----------");
        Date lateDate= DateUtil.getDateHourMinuteSecond(payOrderInfoVO.getShouldReturnTime(),hour,0,0);
        Date lateDateUtil=DateUtil.addDays(lateDate,1);
        OrderJobParams lateRemindJobParams=new OrderJobParams();
        lateRemindJobParams.setOrderNo(payOrderInfoVO.getOrderNo());
        lateRemindJobParams.setOrderExpireTime(lateDateUtil);
        lateRemindJobParams.setTaskType(TaskEnum.LATE_REMIND_JOB);
        payOrderJobService.createExpireRefundJob(lateRemindJobParams);
        LogUtil.info(logger, "-------------第一天的逾期定时任务生成完成-----------");
        //生成下一个逾期费用计算的定时任务
        LogUtil.info(logger, "-------------开始生成第二天逾期计费定时任务-----------");
        Date lateCostDate=DateUtil.getDateHourMinuteSecond(payOrderInfoVO.getShouldReturnTime(),0,0,0);
        Date lateNextCostDateDateUtil=DateUtil.addDays(lateCostDate,2);
        OrderJobParams lateFreeCalJobParams=new OrderJobParams();
        lateFreeCalJobParams.setOrderNo(payOrderInfoVO.getOrderNo());
        lateFreeCalJobParams.setOrderExpireTime(lateNextCostDateDateUtil);
        lateFreeCalJobParams.setTaskType(TaskEnum.CALCULATE_LATE_PAYMENT_JOB);
        payOrderJobService.createExpireRefundJob(lateFreeCalJobParams);
        LogUtil.info(logger, "-------------第二天逾期计费定时任务生成完成-----------");
    }

}
